/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import common from '@/common/index';
import { localCache } from '@/utils';
// import { message } from 'ant-design-vue';
import { ElMessage } from 'element-plus';
import { nextTick, ref, reactive, onMounted } from 'vue';
import { useStore } from 'vuex';

import '@/utils/myPractice/index.ts';

const { initBtnStyle } = common;

export const initLogin = function () {
  initStyle();
};

const initStyle = function () {
  const labels = document.querySelectorAll('.form-control label');
  labels.forEach((label: any) => {
    label.innerHTML = label.innerText
      .split('')
      .map(
        (letter: any, index: number) =>
          `<span style="transition-delay:${index * 50}ms">${letter}</span>`
      )
      .join('');
  });
};

let accountInput: any = null;
export const loginAction = function () {
  const store = useStore();
  const loginLogo = ref({
    value: require('@/assets/imgs/login/loginLogo.svg'),
  });

  const userCount = reactive({
    account: '',
    password: '',
  });

  nextTick(() => {
    initBtnStyle();
    initLogin();
    ElMessage.info('请登录');

    accountInput = document.getElementById('login-account');
  });

  const goLogin = function () {
    const form: any = document.querySelector('.login-form-validator');
    // globalProperties.$router.replace('/main');
    if (accountInput.validity.patternMismatch) {
      accountInput.setCustomValidity('请输入4-6位数字大小写组成的账号');
      userCount.account = '';
    } else {
      accountInput.setCustomValidity('');
    }
    form.submit();
  };

  const formSubmit = function (e: any) {
    e.preventDefault();
    localCache.setCache('loginInfo', {
      account: userCount.account,
      password: userCount.password,
    });

    // setTimeout(() => {
    //   globalProperties.$router.replace('/main');
    // }, 500);
    store.dispatch('login/accountLoginAction', {
      ...userCount,
      name: userCount.account,
    });
  };

  const inputChange = function (e: any, prop: any) {
    const {
      target: { value },
    } = e;
    (userCount as any)[prop] = value;
    accountInput.setCustomValidity('');
  };

  onMounted(() => {
    const loginInfo = localCache.getCache('loginInfo');
    if (loginInfo) {
      Object.assign(userCount, loginInfo);
    }
  });

  return {
    loginLogo,
    goLogin,
    inputChange,
    formSubmit,
    userCount,
  };
};
